<?php
/**
 * Controller for the Chapter-Model
 *
 * PHP versions 4 and 5
 *
 * TutoriumBase (http://tutoriumbase.my-reality.de)
 * Copyright 2012, Miguel Gonzalez (http://my-reality.de)
 *
 *
 * @copyright     Copyright 2012, Miguel Gonzalez (http://my-reality.de)
 * @link          http://tutoriumbase.my-reality.de TutoriumBase
 * @since         TutoriumBase v 0.1
 */

class ChaptersController extends AppController {
    
    var $name = 'Chapters';    
    var $helpers = array('Chapter');
    
        
    /**
     * Add a new chapter to the given tutorial
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function add($tutorial_id) {
        // Retrieving data from database
        $tutorial = $this->Chapter->Tutorial->findById($tutorial_id);
        $tutorial['Chapter'] = Set::sort($tutorial['Chapter'], '{n}.inner_order', 'asc');

        if (empty($tutorial)) {
            // Missing data -> redirect
            $this->redirect(array('controller' => 'tutorials', 'action' => 'index'));
        }
        
        // Re-order and save new chapter data into database
        if (!empty($this->data)) {
            $this->data['Chapter']['id'] = null;
            $this->data['Chapter']['tutorial_id'] = $tutorial_id;
            
            if ($this->data['Chapter']['position'] > count($tutorial['Chapter']))     {
                $this->data['Chapter']['inner_order'] = $this->_getNextOrder($tutorial_id);
            } else {
                $this->_reorderNextElements($tutorial['Chapter'], $this->data['Chapter']['position']);
                $this->data['Chapter']['inner_order'] = $this->data['Chapter']['position'];
            }
            
            if ($this->Chapter->save($this->data)) {
                $this->flashMessage('Erfolg!', 'success');  
                $this->redirect(array(
                     'controller' => 'tutorials',
                     'action'     => 'view/' . $tutorial_id));
            } else {
                 $this->flashMessage('Es sind ein oder mehrere Fehler aufgetreten.', 'fail');
            }
        }        
        
        // Set data
        $this->set('data', $tutorial);
        $this->setPageTitle('Kapitel hinzufügen');
        $this->set('caption', 'Tutorial - Kapitel hinzufügen');
    }
    
    
    
    
    
    /**
     * Edit a chapter with the given id
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function edit($id) {
        if (!empty($id)) {
                $data = $this->Chapter->read(null, $id);
                if (empty($data)) {
                    // Missing data -> redirect
                   $this->redirect(array('controller' => 'tutorials', 'action' => 'index'));
                } else {                    
                    // Load and sort chapters
                    $temp = $this->Chapter->Tutorial->findById($data['Chapter']['tutorial_id']);
                    $temp['Chapter'] = Set::sort($temp['Chapter'], '{n}.inner_order', 'asc');
                    
                    // Save edited data
                    if (!empty($this->data)) {
                        // Reorder elements if position has been changed
                        if ($this->data['Chapter']['position'] != $data['Chapter']['inner_order']) {
                            $this->_reorderElements($temp['Chapter'], $this->data['Chapter']['position'], $data['Chapter']['inner_order']);
                            $this->data['Chapter']['inner_order'] = $this->data['Chapter']['position'];
                        }
                        $this->data['Chapter']['id'] = $id;

                        if ($this->Chapter->save($this->data)) {
                            $this->flashMessage('Chapter wurde erfolgreich bearbeitet!', 'success');
                            $this->redirect(array('controller' => 'tutorials', 'action' => 'view/' . $data['Chapter']['tutorial_id']));
                        } else {
                            $this->flashMessage('Kapitel konnte nicht überschrieben werden!', 'fail');
                        }
                    }
                }
                
                // Set data
                $this->setPageTitle('Kapitel bearbeiten');
                $this->set('caption', 'Kapitel bearbeiten');
                $this->set('data', $temp);
                $this->set('current_data', $data);
            } else {
                // Missing argument -> redirect
                $this->redirect(array('controller' => 'tutorials', 'action' => 'index'));
            }  
    }
    
    
    
    /**
     * Delete a chapter with the given id
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function delete($id) {
        if (empty($id)) {
            // Missing argument -> redirect
            $this->redirect(array('action' => 'index'));
        }

        $temp_chapter = $this->Chapter->read(null, $id);

        if (empty($temp_chapter)) {
            // Missing data -> redirect
            $this->redirect(array('action' => 'index'));
        }

        // 1. Delete Chapter
        if (!$this->Chapter->delete($temp_chapter['Chapter']['id'])) {
            $this->flashMessage('Fehler beim Löschen!', 'error');
            $this->redirect($this->referer());
        }
        
        // Read tutorial data of the given chapter
        $temp_tutorial = $this->Chapter->Tutorial->read(null, $temp_chapter['Chapter']['tutorial_id']);
        
        // If tutorial has no more chapter, delete it
        if (empty($temp_tutorial['Chapter'])) {
            // Delete specific categories
            foreach ($temp_tutorial['CategoryCount'] as $category) {
                if (!$this->Chapter->Tutorial->CategoryCount->delete($category['id'])) {
                    $this->flashMessage('Fehler beim Löschen!', 'error');
                    $this->redirect($this->referer());
                }
            }  
            
            // Delete the tutorial
            if (!$this->Chapter->Tutorial->delete($temp_tutorial['Tutorial']['id'])) {
                $this->flashMessage('Fehler beim Löschen!', 'error');
                $this->redirect($this->referer());
            }            
        } else {
            $counter = 1;            
            // Reorder the entire tutorial
            foreach ($temp_tutorial['Chapter'] as $chapter) {

                $chapter['inner_order'] = $counter;
                $chapter['modified'] = null;
                $counter++;            
                $save_data['Chapter'] = $chapter;
                $this->Chapter->save($save_data);
            }
        }

        // Success
        $this->flashMessage('Kapitel wurde erfolgreich gelöscht.', 'success');
        $this->redirect($this->referer());
    }
    
    
    
    
    /**
    * Function to rebuild the inner order of all next elements
    *
    * @author Miguel Gonzalez
    * @version 1.0
    * @since 02-01-2011
    *
    * @param <array> $data data to order
    * @param <int> $source_pos position of the source element
    */
    function _reorderNextElements($data, $source_pos) {      
        foreach($data as $elem) {
            if ($elem['inner_order'] >= $source_pos) {
                ++$elem['inner_order'];
                $save_data['Chapter'] = $elem;
                $this->Chapter->save($save_data);
            }
        }
    }
    
    
        
    
    /**
     * Function to rebuild the inner order of all elements.
     *
     * @author Miguel Gonzalez
     * @version 1.0
     * @since 02-01-2011
     *
     *
     */
    function _reorderElements($data, $source_pos, $old_pos) {        
        if ($source_pos != $old_pos) {

            if ($source_pos < $old_pos) {
                foreach ($data as $elem) {
                        if ($elem['inner_order'] >= $source_pos && $elem['inner_order'] <= $old_pos) {
                            ++$elem['inner_order'];
                            $save_data['Chapter'] = $elem;
                            $this->Chapter->save($save_data);
                        }
                    }                
            } else {
                foreach ($data as $elem) {
                        if ($elem['inner_order'] >= $old_pos && $elem['inner_order'] <= $source_pos) {
                            --$elem['inner_order'];
                            $save_data['Chapter'] = $elem;
                            $this->Chapter->save($save_data);
                        }
                    }
            }                
       }
    }
    
    
    

    /**
     * Function to find out the next available order for the specific tutorial
     *
     * @author Miguel Gonzalez
     * @version 1.0
     * @since 29-12-2010
     *
     * @param <type> $parent_id ID of the parent tutorial
     * @return int
     */
    function _getNextOrder($parent_id) {
        $temp = $this->Chapter->Tutorial->findById($parent_id);        
        if (empty($temp)) return null;
        if (count($temp['Chapter']) == 0) return 1;        
        return $temp['Chapter'][count($temp['Chapter']) - 1]['inner_order'] + 1;
    }
}
?>
